package com.bawei.mall.product.controller;

import com.bawei.common.core.domain.R;
import com.bawei.common.core.web.domain.AjaxResult;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.domain.MallProductAddrs;
import com.bawei.mall.product.service.IMallProductAddrsService;
import com.bawei.mall.product.utils.AnalyzeAddres;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author：作者姓名
 * @Package：com.bawei.mall.product.controller
 * @Project：mall_cloud
 * @name：MallProductAddrsController
 * @Date：2024/6/29 13:43
 */
@RestController
@RequestMapping("/address")
public class MallProductAddrsController {

    @Autowired
    private IMallProductAddrsService mallProductAddrsControllerService;

    @Autowired
    private AnalyzeAddres analyzeAddres;


    @GetMapping("/list")
    public R<List<MallProductAddrs>> MallProductAddrs(){
        Long userId = SecurityUtils.getUserId();
        return R.ok(mallProductAddrsControllerService.selectMallProductAddrs(userId));
    }

    @GetMapping("/userAddrs/{allAddress}")
    public AjaxResult userAddrs(@PathVariable("allAddress") String allAddress){
        String allAddres = analyzeAddres.analyzeAddres(allAddress);
        MallProductAddrs address = new MallProductAddrs();
        try {
            // 使用 ObjectMapper 解析 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(allAddres);
            JsonNode data = jsonNode.get("data");
            // 获取具体字段值
            address.setProvince(data.get("province").asText());
            address.setCity(data.get("city").asText());
            address.setRegion(data.get("county").asText());
            address.setDetailAddress(data.get("town").asText());
            address.setPhoneNumber(data.get("phoneNum").asText());
            address.setName(data.get("person").asText());
            address.setPostCode(data.get("detail").asText());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(address);
    }

    @PostMapping("/addAddress")
    public AjaxResult userAddrs(@RequestBody MallProductAddrs mallProductAddrs){
        mallProductAddrsControllerService.addMallProductAddrs(mallProductAddrs);
        return AjaxResult.success();
    }



}
